﻿using System;
using Microsoft.SharePoint;

namespace SIMSProject.Common
{
    public static class SPListItemExtension
    {
        public static T GetItemValue<T>(this SPListItem item, string name)
        {
            var value = item[name];
            if (value == null)
            {
                return default(T);
            }

            try
            {
                return (T) value;
            }
            catch(InvalidCastException)
            {
                return (T) Convert.ChangeType(value, typeof (T));
            }
        }

        public static int GetItemLookupIdValue(this SPListItem item, string name)
        {
            var value = item[name];
            if (value != null)
            {
                var split = Convert.ToString(value).Split(new[] {";#"}, StringSplitOptions.None);
                if (split.Length == 2)
                {
                    return Convert.ToInt32(split[0]);
                }
            }

            return 0;
        }
    }
}